/*Copyright ©2015 TommyLemon(https://github.com/TommyLemon)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
limitations under the License.*/

package zuo.biao.library.util;

import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.RunningProcessInfo;
import ohos.aafwk.content.Intent;
import ohos.agp.window.dialog.CommonDialog;
import ohos.agp.window.dialog.ToastDialog;
import ohos.app.Context;
import ohos.app.IAbilityManager;
import ohos.bundle.IBundleManager;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.media.image.ImagePacker;
import ohos.media.image.PixelMap;
import ohos.miscservices.pasteboard.PasteData;
import ohos.miscservices.pasteboard.SystemPasteboard;
import ohos.net.NetManager;
import ohos.utils.net.Uri;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

/**通用操作类
 * @author Lemon
 * @use CommonUtil.xxxMethod(...);
 */
public class CommonUtil {
    private static final String TAG = "CommonUtil";

    public CommonUtil() {
        /* 不能实例化* */
    }

    //电话<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    /**打电话
     * @param context 上下文
     * @param phone 手机号
     */
    @Deprecated
    public static void call(Ability context, String phone) {
    }

    //电话>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
//信息<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    /**发送信息，多号码
     * @param context 上下文
     * @param phoneList 手机
     */
    @Deprecated
    public static void toMessageChat(Ability context, List<String> phoneList){
        if (context == null || phoneList == null || phoneList.size() <= 0) {
            showShortToast(context, "请先选择号码哦~");
            return;
        }

        String phones = "";
        for (int i = 0; i < phoneList.size(); i++) {
            phones += phoneList.get(i) + ";";
        }
        toMessageChat(context, phones);
    }
    /**发送信息，单个号码
     * @param context 上下文
     * @param phone 手机
     */
    @Deprecated
    public static void toMessageChat(Ability context, String phone){
        if (context == null || StringUtil.isNotEmpty(phone, true) == false) {
            return;
        }

    }

    //信息>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    /**分享信息
     * @param context 上下文
     * @param toShare 是否分享
     */
    @Deprecated
    public static void shareInfo(Ability context, String toShare) {
        if (context == null || StringUtil.isNotEmpty(toShare, true) == false) {
            return;
        }

    }

    /**发送邮件
     * @param context 上下文
     * @param emailAddress email
     */
    @Deprecated
    public static void sendEmail(Ability context, String emailAddress) {
        if (context == null || StringUtil.isNotEmpty(emailAddress, true) == false) {
            return;
        }
    }
    /**打开网站
     * @param context context
     * @param webSite webSite
     */
    public static void openWebSite(Ability context, String webSite) {
        if (context == null || StringUtil.isNotEmpty(webSite, true) == false) {
            Log.error(TAG, "openWebSite  context == null || StringUtil.isNotEmpty(webSite, true) == false >> return;");
            return;
        }

        toActivity(context, new Intent());
    }

    /**复制文字
     * @param context context
     * @param value value
     */
    public static void copyText(Context context, String value) {
        if (context == null || StringUtil.isNotEmpty(value, true) == false) {
            Log.error(TAG, "copyText  context == null || StringUtil.isNotEmpty(value, true) == false >> return;");
            return;
        }

        PasteData cD = PasteData.creatPlainTextData(value);
        SystemPasteboard clipboardManager = (SystemPasteboard) SystemPasteboard.getSystemPasteboard(context);
        clipboardManager.setPasteData(cD);
        showShortToast(context, "已复制" + value);
    }

    // 启动新Activity方法<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    /**
     * 打开新的Activity，向左滑入效果
     * @param intent intent
     * @param context context
     */
    public static void toActivity(final Ability context, final Intent intent) {
        toActivity(context, intent, true);
    }

    /**打开新的Activity
     * @param intent intent
     * @param showAnimation showAnimation
     * @param context context
     */
    public static void toActivity(final Ability context, final Intent intent, final boolean showAnimation) {
        toActivity(context, intent, -1, showAnimation);
    }
    /**打开新的Activity，向左滑入效果
     * @param intent intent
     * @param requestCode requestCode
     * @param context context
     */
    public static void toActivity(final Ability context, final Intent intent, final int requestCode) {
        toActivity(context, intent, requestCode, true);
    }
    /**打开新的Activity
     * @param intent intent
     * @param requestCode requestCode
     * @param showAnimation showAnimation
     * @param context context
     */
    public static void toActivity(
            final Ability context, final Intent intent, final int requestCode, final boolean showAnimation) {
        if (context == null || intent == null) {
            return;
        }
        EventHandler handler = new EventHandler(EventRunner.getMainEventRunner());
        handler.postTask(
                new Runnable() {
                    @Override
                    public void run() {
                        if (requestCode < 0) {
                            context.startAbility(intent);
                        } else {
                            context.startAbilityForResult(intent, requestCode);
                        }
                        if (showAnimation) {
                            context.setTransitionAnimation(0, 0);
                        } else {
                            context.setTransitionAnimation(0, 0);
                        }
                    }
                });
    }
    // 启动新Activity方法>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    // 显示与关闭进度弹窗方法<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    private static CommonDialog progressDialog = null;

    /**展示加载进度条,无标题
     * @param stringResId stringResId
     * @param context context
     */
    public static void showProgressDialog(Ability context, int stringResId) {
        try {
            showProgressDialog(context, null, ResTUtil.getString(context, stringResId));
        } catch (Exception e) {
            Log.error(
                    TAG,
                    "showProgressDialog  showProgressDialog(Context context, null,"
                            + " context.getResources().getString(stringResId));");
        }
    }
    /**展示加载进度条,无标题
     * @param context c
     * @param dialogMessage  d
     */
    public void showProgressDialog(Ability context, String dialogMessage) {
        showProgressDialog(context, null, dialogMessage);
    }
    /**展示加载进度条
     * @param dialogTitle 标题
     * @param dialogMessage 信息
     * @param context c
     */
    public static void showProgressDialog(final Ability context, final String dialogTitle, final String dialogMessage) {
        if (context == null) {
            return;
        }
        EventHandler handler = new EventHandler(EventRunner.getMainEventRunner());
        handler.postTask(
                new Runnable() {
                    @Override
                    public void run() {
                        if (progressDialog == null) {
                            progressDialog = new CommonDialog(context);
                        }
                        if (progressDialog.isShowing() == true) {
                            progressDialog.hide();
                            progressDialog.destroy();
                        }
                        if (dialogTitle != null && !"".equals(dialogTitle.trim())) {
                            progressDialog.setTitleText(dialogTitle);
                        }
                        if (dialogMessage != null && !"".equals(dialogMessage.trim())) {
                            progressDialog.setContentText(dialogMessage);
                        }
                        progressDialog.setAutoClosable(false);
                        progressDialog.setCornerRadius(100);
                        progressDialog.show();
                    }
                });
    }

    /**
     * 隐藏加载进度
     * @param context context
     */
    public static void dismissProgressDialog(Ability context) {
        if (context == null || progressDialog == null || progressDialog.isShowing() == false) {
            return;
        }
        EventHandler handler = new EventHandler(EventRunner.getMainEventRunner());
        handler.postTask(
                new Runnable() {
                    @Override
                    public void run() {
                        progressDialog.hide();
                        progressDialog.destroy();
                    }
                });
    }
    // 显示与关闭进度弹窗方法>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    // show short toast 方法<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    /**快捷显示short toast方法，需要long toast就用 Toast.makeText(string, Toast.LENGTH_LONG).show(); ---不常用所以这个类里不写
     * @param context context
     * @param stringResId stringResId
     */
    public static void showShortToast(final Context context, int stringResId) {
        try {
            showShortToast(context, ResTUtil.getString(context, stringResId));
        } catch (Exception e) {
            Log.error(
                    TAG,
                    "showShortToast  context.getResources().getString(resId) >>  catch (Exception e) {"
                            + e.getMessage());
        }
    }
    /**快捷显示short toast方法，需要long toast就用 Toast.makeText(string, Toast.LENGTH_LONG).show(); ---不常用所以这个类里不写
     * @param context context
     * @param string string
     */
    public static void showShortToast(final Context context, final String string) {
        showShortToast(context, string, false);
    }
    /**快捷显示short toast方法，需要long toast就用 Toast.makeText(string, Toast.LENGTH_LONG).show(); ---不常用所以这个类里不写
     * @param string string
     * @param context context
     * @param isForceDismissProgressDialog isForceDismissProgressDialog
     */
    public static void showShortToast(
            final Context context, final String string, final boolean isForceDismissProgressDialog) {
        if (context == null) {
            return;
        }
        new ToastDialog(context).setContentText(string).show();
    }
    // show short toast 方法>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    /**保存照片到SD卡上面
     * @param path path
     * @param photoName photoName
     * @param formSuffix formSuffix
     * @param photoBitmap photoBitmap
     * @return String
     */
    public static String savePhotoToSDCard(String path, String photoName, String formSuffix, PixelMap photoBitmap) {
        if (photoBitmap == null
                || StringUtil.isNotEmpty(path, true) == false
                || StringUtil.isNotEmpty(
                                StringUtil.getTrimedString(photoName) + StringUtil.getTrimedString(formSuffix), true)
                        == false) {
            Log.error(
                    TAG,
                    "savePhotoToSDCard photoBitmap == null || StringUtil.isNotEmpty(path, true) == false"
                            + "|| StringUtil.isNotEmpty(photoName, true) == false) >> return null");
            return null;
        }

        File dir = new File(path);
        if (!dir.exists()) {
            boolean ismk = dir.mkdirs();
        }
        File photoFile = new File(path, photoName + "." + formSuffix); // 在指定路径下创建文件
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(photoFile);
            ImagePacker packer = ImagePacker.create();
            ImagePacker.PackingOptions options = new ImagePacker.PackingOptions();
            if (packer.initializePacking(fileOutputStream, options)) {
                fileOutputStream.flush();
            }
        } catch (FileNotFoundException e) {
            Log.error(TAG, "savePhotoToSDCard catch (FileNotFoundException e) { " + e.getMessage());
            boolean dl = photoFile.delete();
        } catch (IOException e) {
            Log.error(TAG, "savePhotoToSDCard catch (IOException e) { " + e.getMessage());
            boolean dl = photoFile.delete();
        } finally {
            try {
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                Log.error(TAG, "savePhotoToSDCard } catch (IOException e) {\n " + e.getMessage());
            }
        }

        try {
            return photoFile.getCanonicalPath();
        } catch (IOException e) {
            Log.error("IOException", e.getMessage());
        }
        return null;
    }

    /**
     * 检测网络是否可用
     *
     * @param context context
     * @return boolean
     */
    public static boolean isNetWorkConnected(Context context) {
        if (context != null) {
            NetManager mConnectivityManager = NetManager.getInstance(context);
            if (mConnectivityManager != null) {
                return mConnectivityManager.hasDefaultNet();
            }
        }

        return false;
    }

    /**获取顶层 Processes name
     * @param context context
     * @return String
     */
    public static String getTopActivity(Context context) {
        IAbilityManager manager = (IAbilityManager) context.getAbilityManager();
        List<RunningProcessInfo> runningTaskInfos = manager.getAllRunningProcesses();

        return runningTaskInfos == null ? "" : runningTaskInfos.get(0).getProcessName();
    }

    /**检查是否有位置权限
     * @param context context
     * @return boolean
     */
    public static boolean isHaveLocationPermission(Context context) {
        return isHavePermission(context, "android.permission.ACCESS_COARSE_LOCATION")
                || isHavePermission(context, "android.permission.ACCESS_FINE_LOCATION");
    }
    /**检查是否有权限
     * @param context context
     * @param name name
     * @return boolean
     */
    public static boolean isHavePermission(Context context, String name) {
        try {
            return IBundleManager.PERMISSION_GRANTED == context.verifyCallingPermission(name);
        } catch (Exception e) {
            Log.error("Exception", e.getMessage());
        }
        return false;
    }
}
